#include <opencv2/opencv.hpp>
#include <opencv2/dnn.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>

using namespace cv; //Must Need Write cv
using namespace std;

#define ALPHA 0.2
#define BETA  0.8
#define GAMMA 0

/*
 * ./opencv_addWeighted <image1> <image2>
 *
 */

int main(int argc, char** argv)
{
    if (argc < 3) {
        std::cerr << "Usage: " << argv[0] << " <image1> <image2> " << std::endl;
        return -1;
    }

    //区分两种不同的情况1.两张图片尺寸一至，2.不一致
    Mat src1 = imread(argv[1]);
    if(src1.empty())
    {
        printf("get src1 err\n");
        return -1;
    }
    else
    {
        printf("width = %d,height = %d,channel = %d \n", src1.cols, src1.rows, src1.channels());
    }

    
    Mat src2 = imread(argv[2]);
    if(src2.empty())
    {
        printf("get src2 err\n");
        return -1;
    }
    else
    {
        printf("width = %d,height = %d,channel = %d \n", src2.cols, src2.rows, src2.channels());
    }

    Mat result;
    string output_filename;

    // 检查图像尺寸是否相同
    if (src1.size() == src2.size())
    {
        printf("same size.......\n");
        double alpha = 0.4;
        double beta = 1 - alpha;
        addWeighted(src1, alpha, src2, beta, 0, result);
        output_filename = "addweighted_samesize.jpg";
    }
    else
    {
        Mat max_src = src1;
        Mat min_src = src1;
        
        if(src1.rows * src1.cols > src2.rows * src2.cols)
        {
            max_src = src1;
            min_src = src2;
        }
        else
        {
            max_src = src2;
            min_src = src1;
        }
        
        // 创建大图的副本作为结果
        max_src.copyTo(result);//神来之笔    
        
        Mat img_src_roi = result(Rect(100, 100, min_src.cols, min_src.rows));
        if(img_src_roi.empty())
        {
            printf("get img_src_roi  err\n");
            return -1;
        }
        else
        {
            printf("width = %d,height = %d,channel = %d \n", img_src_roi.cols, img_src_roi.rows, img_src_roi.channels());
        }
        
        addWeighted(min_src, ALPHA, img_src_roi, BETA, GAMMA, img_src_roi);
        output_filename = "addweighted_diff.jpg"; 
    
    }

    

    bool success = imwrite(output_filename, result);
    if (!success) {
        printf("Failed to save image!\n");
        return -1;
    }

    printf("Image saved as: %s\n", output_filename.c_str());
    
    return 0;
}


